"""
This script is used to run all the test of openttd performance
"""
import Process ,os,time,  sys, math,Analysis
from threading import Timer
from Performance import Performance
from Configuration import Configuration
import test1c_server

def expVarChange(expName, var):
    if(expName == "1a1"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setAI(var)
    if(expName == "1a5"):
        Configuration.set("difficulty", "max_no_competitors", 1)
        Configuration.setSingleAI(var)
    if(expName == "1a6-64"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
        Configuration.set("game_creation", "map_x", 6)
        Configuration.set("game_creation", "map_y", 6)

    if(expName == "1a6-128"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
        Configuration.set("game_creation", "map_x", 7)
        Configuration.set("game_creation", "map_y", 7)

    if(expName == "1a6-256"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
        Configuration.set("game_creation", "map_x", 8)
        Configuration.set("game_creation", "map_y", 8)

    if(expName == "1a6-1024"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
        Configuration.set("game_creation", "map_x", 10)
        Configuration.set("game_creation", "map_y", 10)
    if(expName == "1a6-2048"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
        Configuration.set("game_creation", "map_x", 11)
        Configuration.set("game_creation", "map_y", 11)
    if expName == "1a2":
        Configuration.set("game_creation", "map_x", var)
        Configuration.set("game_creation", "map_y", var)
    if expName == "1a3":
        Configuration.set("difficulty", "number_towns", var)
        Configuration.set("difficulty", "number_industries", var)
    if expName == "1a4":
        Configuration.set("difficulty", "max_no_competitors", 16)
        Configuration.setRandomAI(16)
        Configuration.set("game_creation", "map_x", 11)
        Configuration.set("game_creation", "map_y", 11)
    if(expName == "1a6" or expName == "2a6"):
        Configuration.set("difficulty", "max_no_competitors", var)
        Configuration.setRandomAI(var)
    return True

minVars = { "1a1":1, "1a2":11, "1a3":1, "1a4":1, "1c":1, "1a6-1024":1, 
           "1a6-2048":1, "1a6-256":1,  "1a5":6, "1a6":1,
           "2a6":1}
maxVars = { "1a1":16, "1a2":11, "1a3":4, "1a4":1, "1c":4, 
           "1a6-1024":16, "1a6-2048":16, "1a6-256":4, "1a5":16, "1a6":16,
           "2a6":16}

#differnt cluster has different configuration.....................
servers = [
#           "fs0.das3.cs.vu.nl"
#           ,
#           "fs1.das3.liacs.nl",
#           "fs2.das3.science.uva.nl",
           "fs3.das3.tudelft.nl"
#           , "fs4.das3.science.uva.nl"
           ]

def findServer(expName, factor):
    rank = allocateStatus(expName, factor)
    return servers[rank % len(servers)]

def allocateStatus(expName, factor):
    i = 0
    for k in minVars.keys():
        if k == expName:
            break;
        i = i + 1
    rank = 0
    for j in (0, i):
        name = minVars.keys()[j]
        rank = rank + (maxVars[name] - minVars[name] + 1)
    rank = rank + factor
    return rank

def isStillRunning(expName, factor):
    cmd =  "qstat |grep sshen";
    servername = findServer(expName, factor)
    cmd = "ssh -i "+ Configuration.sshKey + " sshen@"+ servername + " '" + cmd + "'";
    file = os.popen(cmd)
    lines = file.readlines()
    if len(lines) > 0:
        return True;
    return False;

def runExpInServer(id, expName, maxYear, factor):
    timelimit = 1000 * maxYear
    print "-------------------------------------------------"
    cmd = "prun -v -np 16 -1 -t %d "%timelimit + "python /home/sshen/OpenTTDTestingDas3/src/JobExecution.py " + "%d"%id + " " + expName + " " + "%d"%maxYear + " " + "%d"%factor
    servername = findServer(expName, factor)
    print "ssh -i "+ Configuration.sshKey + " sshen@"+ servername + " '" + cmd + "'& "
    os.system("ssh -i "+ Configuration.sshKey + " sshen@"+ servername + " '" + cmd + "'&")
    print "-----------------------------------------------------"
    return True

def removeAutoSaveOnServer(servername):
    print "ssh -i "+ Configuration.sshKey + " sshen@"+servername + " 'rm -fr /home/sshen/.openttd/save/autosave' &"
    os.system("ssh -i "+ Configuration.sshKey + " sshen@"+servername + " 'rm -fr /home/sshen/.openttd/save/autosave' &");

def copyfile(servername):
#    filename = "/cygdrive/c/users/q/documents/openttd/openttd.cfg"
    filename = "../openttd.cfg"
#    filename = '\"C:\\Users\\Q\\Documents\\OpenTTD\\openttd.cfg\"'
#    print "scp -i "+ Configuration.sshKey + " " +  filename + " sshen@" + servername + ":/home/sshen/.openttd/ "
    print "scp -i "+ Configuration.sshKey + " " +  filename + " sshen@" + servername + ":/home/sshen/run/ "
    os.system("scp -i "+ Configuration.sshKey + " " + filename + " sshen@" + servername + ":/home/sshen/run/ ")
#    filename = "\"c:\\cygwin\\home\\Q\\OpenTTD\\scripts\\game_start.scr\""
#    filename = "/cygdrive/c/cygwin/home/q/openttd/scripts/game_start.scr"
    filename = "../game_start.scr"
#    print "scp -i "+ Configuration.sshKey + " " + filename + " sshen@" + servername + ":/home/sshen/openttd/1.0.5/bin/scripts/game_start.scr"
    print "scp -i "+ Configuration.sshKey + " " + filename + " sshen@" + servername + ":/home/sshen/run/scripts/game_start.scr"
    os.system("scp -i "+ Configuration.sshKey + " " + filename + " sshen@" + servername + ":/home/sshen/run/scripts/game_start.scr")

def changeConfigurationAndSendtoServer(expName, factor):
    Configuration.initExp(expName)
    expVarChange(expName, factor)
    server = findServer(expName, factor)
    copyfile(server)
    removeAutoSaveOnServer(server)
    return True

#expNames = ["1a1-1024", "1a1-2048", "1a4", "1a1-64", "1a1-128", "1a1-256"]
expNames = ["1a6-2048", "1a4"]
Configuration = Configuration()

def testAll(maxYear):
    Configuration.increaseId()
    id = Configuration.getId();    
    count = 0
    for expName in expNames:
        if expName == "1a4":
            maxYear = 10
        else : maxYear = 1
        for i in xrange(minVars[expName], maxVars[expName]+1):
            while(isStillRunning(expName, i)):
                time.sleep(30);
            changeConfigurationAndSendtoServer(expName, i)
#            testSingle(expId, expName, maxYear, factor, path = "")
            runExpInServer(id, expName, maxYear, i)
            pth = allocateStatus(expName, i)
            count = count + 1
            time.sleep(700 * maxYear)
            
#            if count % 4 == 0 :
#                print "sleep"
#                time.sleep(900)

    
if __name__ == "__main__":
    testAll(1)